﻿using FluentNHibernate.Conventions;
using FluentNHibernate.Conventions.Instances;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace Gecko.Util
{
    public class CascadeConvention : IHasManyConvention, IReferenceConvention
    {
        public void Apply(IManyToOneInstance instance)
        {
            var property = instance.Property.MemberInfo;

            if (!HasAttribute(property)) return;

            Console.WriteLine("CascadeAll on {0}.{1}", property.DeclaringType.Name, property.Name);

            instance.Cascade.All();
        }

        public void Apply(IOneToManyCollectionInstance instance)
        {
            var property = instance.Member;

            if (!HasAttribute(property)) return;

            Console.WriteLine("CascadeAllDeleteOrphan on {0}.{1}", property.DeclaringType.Name, property.Name);

            instance.Cascade.AllDeleteOrphan();
        }

        bool HasAttribute(ICustomAttributeProvider provider)
        {
            return provider.GetCustomAttributes(typeof(CascadeAttribute), false).Length == 1;
        }
    }
}